package org.aersoft.jokebook.activities;

import java.util.ArrayList;

import org.aersoft.jokebook.R;
import org.aersoft.jokebook.beans.ItemBean;
import org.aersoft.jokebook.core.Constants;
import org.aersoft.jokebook.dao.AppDAO;
import org.aersoft.jokebook.dao.api.IAppDAO;
import org.aersoft.jokebook.fragments.MainFragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Activity main class of application.
 * @author Danilo de Godoy Carolino
 */
public class MainActivity extends Activity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private ArrayList<ItemBean> arrayBeans;
    private IAppDAO appDAO;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

        appDAO = new AppDAO().getContext(this);
        arrayBeans = appDAO.getJokeAllCategories();
        ArrayList<String> titleList = new ArrayList<String>();
        for (ItemBean item : arrayBeans) {
            int listSize = appDAO.getJokeListByCategory(item.getCategoryId()).size();
            titleList.add(item.getCategoryName() + Constants.OPEN_BRACKET + listSize + Constants.CLOSE_BRACKET);
        }
        appDAO.close();

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, titleList));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(getTitle());
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(getTitle());
                invalidateOptionsMenu();
            }
        };

        getFragmentManager().beginTransaction().replace(R.id.content_frame, new MainFragment()).commit();
        mDrawerList.setItemChecked(0, false);
        mDrawerLayout.closeDrawer(mDrawerList);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    /**
     * Method to redirect for app creator website.
     * @param view of {@link View} type.
     */
    public void toWebsite(View view) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.WEBSITE));
        startActivity(browserIntent);
    }

    /**
     * Method to send e-mail for system app creator.
     * @param view of {@link View} type.
     */
    public void sendMail(View view) {
        Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.MAILTO, Constants.CREATOR_MAIL, null));
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, Constants.MAIL_TITLE);
        startActivity(emailIntent);
    }

    /**
     * Get the category ID parameter and send it to other class, {@link br.com.jokebook.activities.CategoryActivity} Class,
     * like a parameter, too.
     * @param id of {@link Integer} type.
     */
    private void goToCategory(int id) {
        Intent intent = new Intent(this, CategoryActivity.class);
        intent.putExtra(Constants.CATEGORY, id);
        startActivity(intent);
    }

    /**
     * Get the category ID, by the onClick event on layout buttons, and send it
     * to the goToCategory() method, like a parameter.
     * @param view do tipo {@link android.view.View}
     */
    public void onClickEvent(View view) {
        Fragment fragment = new MainFragment();
        getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
        mDrawerLayout.closeDrawer(mDrawerList);
        switch (view.getId()) {
            case (R.id.button1): goToCategory(arrayBeans.get(0).getCategoryId()); break;
            case (R.id.button2): goToCategory(arrayBeans.get(1).getCategoryId()); break;
            case (R.id.button3): goToCategory(arrayBeans.get(2).getCategoryId()); break;
            case (R.id.button4): goToCategory(arrayBeans.get(3).getCategoryId()); break;
            case (R.id.button5): goToCategory(arrayBeans.get(4).getCategoryId()); break;
            case (R.id.button6): goToCategory(arrayBeans.get(5).getCategoryId()); break;
            default: break;
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        getActionBar().setTitle(title);
    }

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) return true;
        switch (item.getItemId()) {
            case (R.id.action_websearch):
                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
                if (intent.resolveActivity(getPackageManager()) != null) startActivity(intent);
                else Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
                return true;
            default: return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Listener private class for the click event of options bar.
     */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Fragment fragment = new MainFragment();
            getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
            mDrawerLayout.closeDrawer(mDrawerList);
            goToCategory(arrayBeans.get(position).getCategoryId());
        }
    }

}
